<?php

namespace App\Http\Controllers\Admin;

use App\Models\WeixinMenu;
use App\WeChat\WechatDefaultConfig;
use App\WeChat\WxApi\WxMaterialApi;
use App\WeChat\WxApi\WxMenuApi;
use App\WeChat\WxApi\WxNewsApi;
use Illuminate\Http\Request;

class WeixinController extends BaseController
{
    use WechatDefaultConfig;
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     */
    public function menu(){
        if ($this->isOnSubmit()) {
            $delete = $this->request->post('delete');
            if ($delete) {
                foreach ($delete as $id) {
                    WeixinMenu::where('id', $id)->delete();
                }
            }

            $menulist = $this->request->post('menulist');
            if ($menulist) {
                foreach ($menulist as $id=>$menu) {
                    if ($menu['name']) {
                        if ($id > 0) {
                            WeixinMenu::where('id', $id)->update($menu);
                        }else {
                            WeixinMenu::insert($menu);
                        }
                    }
                }
            }
            return $this->messager()->message(trans('sysmessage.info update success'))->render();
        }else {

            $menus = WeixinMenu::with('childs')->where('fid', 0)->orderBy('id')->get();
            $this->assign([
                'menus'=>$menus,
                'menu_types'=>trans('weixin.menu_types')
            ]);

            return $this->view('admin.weixin.menu');
        }
    }

    public function newMenu()
    {
        $id = intval($this->request->input('id'));
        $fid = intval($this->request->input('fid'));

        if ($this->isOnSubmit()) {
            $menu = $this->request->input('menu');
            if ($id) {
                WeixinMenu::where('id', $id)->update($menu);
            } else {
                WeixinMenu::insert($menu);
            }

            return ajaxReturn();
        } else {
            $menu = WeixinMenu::find($id);
            $menu_types = trans('weixin.menu_types');

            return $this->view('admin.weixin.newmenu', compact('id', 'menu', 'fid', 'menu_types'));
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function applyMenu() {


        $menus = WeixinMenu::with('childs')->where('fid', 0)->orderBy('id')->get();
        if ($menus) {
            $buttons = [];
            foreach ($menus as $menu) {
                if ($menu->childs->count() > 0) {
                    $sub_button = [];
                    foreach ($menu->childs as $child){
                        //网页
                        if ($child->type == 'view') {
                            if ($child->name && $child->url){
                                $sub_button[] = [
                                    'type'=>$child->type,
                                    'name'=>$child->name,
                                    'url'=>$child->url
                                ];
                            }
                        }elseif ($child->type == 'view_limited'){
                            if ($child->media_id) {
                                $sub_button[] = [
                                    'type'=>$child->type,
                                    'name'=>$child->name,
                                    'media_id'=>$child->media_id
                                ];
                            }
                        } else {
                            if ($child->key) {
                                $sub_button[] = [
                                    'type'=>$child->type,
                                    'name'=>$child->name,
                                    'key'=>$child->key
                                ];
                            }
                        }
                    }
                    $buttons[] = [
                        'name'=>$menu->name,
                        'sub_button'=>$sub_button
                    ];
                } else {
                    if ($menu->type == 'view') {
                        if ($menu->url) {
                            $buttons[] = [
                                'type'=>$menu->type,
                                'name'=>$menu->name,
                                'url'=>$menu->url
                            ];
                        }
                    } elseif ($menu->type == 'view_limited'){
                        if ($menu->media_id) {
                            $buttons[] = [
                                'type'=>$menu->type,
                                'name'=>$menu->name,
                                'media_id'=>$menu->media_id
                            ];
                        }
                    } else {
                        if ($menu->key) {
                            $buttons[] = [
                                'type'=>$menu->type,
                                'name'=>$menu->name,
                                'key'=>$menu->key
                            ];
                        }
                    }
                }
            }

            $res = $this->officialAccount()->menu->create($buttons);
            if ($res['errcode'])
            {
                return ajaxError($res['errcode'], $res['errmsg']);
            } else {
                return ajaxReturn($res);
            }
        } else {
            return ajaxError(404, 'not found');
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function removeMenu(){
        $res = $this->officialAccount()->menu->delete();
        if ($res['errcode']) {
            return ajaxError($res['errcode'], $res['errmsg']);
        } else {
            return ajaxReturn($res);
        }
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|mixed
     * @throws \Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function material() {
        $type = $this->request->get('type');
        $type = $type ? $type : 'image';
        $this->assign([
            'material_types'=>trans('weixin.material_types'),
            'type'=>$type,
            'items'=>[]
        ]);

        $page = max(array(1, intval($this->request->get('page'))));
        $res = $this->officialAccount()->material->list($type, ($page-1)*20, 20);
        if (isset($res['item'])) {
            $totalCount = $res['total_count'];
            $this->assign([
                'items'=>$res['item'],
                'pagination'=>mutipage($page, 20, $totalCount, ['type'=>$type], false)
            ]);

            return $this->view('admin.weixin.material');
        }else {
            return $res;
        }
    }

    /**
     *
     */
    public function addMaterial(){

    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function batchDeleteMaterial(Request $request)
    {
        $items = $request->input('items');
        if (is_array($items))
        {
            foreach ($items as $media_id)
            {
                WxMaterialApi::delete($media_id);
            }
        }

        return ajaxReturn();
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|mixed
     * @throws \Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function news() {
        if ($this->isOnSubmit()) {
            $materials = $this->request->post('materials');
            foreach ($materials as $media_id) {
                WxNewsApi::deleteNews($media_id);
            }
            return $this->messager()->message(trans('sysmessage.info delete success'))->render();
        }else {

            $this->assign([
                'itemlist'=>[],
                'pagination'=>''
            ]);
            $page = $this->request->get('page');
            $page = max($page, 1);
            $json = WxNewsApi::batchgetNews(($page - 1)*20, 20);
            $news = json_decode($json, true);
            if (isset($news['item'])) {
                $itemlist = $news['item'];
                $totalcount = $news['total_count'];
                $this->data['pagination'] = mutipage($page, 20, $totalcount, null, false);

                if ($itemlist) {
                    foreach ($itemlist as $item){
                        $item['title'] = $item['content']['news_item'][0]['title'];
                        $item['thumb_media_id'] = $item['content']['news_item'][0]['thumb_media_id'];
                        $item['item_count'] = count($item['content']['news_item']);
                        unset($item['content']);
                        $this->data['itemlist'][$item['media_id']] = $item;
                    }
                }

                return $this->view('admin.weixin.news');
            }else {
                return $json;
            }
        }
    }

    /**
     *
     */
    public function addNews(){

    }

    public function batchDeleteNews(Request $request)
    {
        $items = $request->input('items');
        if (is_array($items))
        {
            foreach ($items as $media_id)
            {
                WxNewsApi::deleteNews($media_id);
            }
        }

        return ajaxReturn();
    }

    /**
     * @return mixed
     * @throws \Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function viewImage(){
        $media_id = $this->request->get('media_id');
        return WxMaterialApi::get($media_id);
    }
}
